package com.accenture.fd.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.accenture.fd.entity.User;
import com.accenture.fd.service.UserService;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

@RestController
public class ExportController {

	@Autowired
	private UserService userService;

	@RequestMapping("/export")
	public void export(HttpServletResponse response) {

        // 取出数据
		User user = this.userService.getUser("test");

        // 编辑数据
		List<User> list = new ArrayList<>();
		list.add(user);
		list.add(user);

//		list.add(new User("zhangsan", "1231", LocalDateTime.now()));
//
//		list.add(new User("zhangsan1", "1232", LocalDateTime.now()));
//
//		list.add(new User("zhangsan2", "1233", LocalDateTime.now()));
//
//		list.add(new User("zhangsan3", "1234", LocalDateTime.now()));
//
//		list.add(new User("zhangsan4", "1235", LocalDateTime.now()));
//
//		list.add(new User("zhangsan5", "1236", LocalDateTime.now()));

		// 创建writer，默认创建xls格式 true代表xlsx
		ExcelWriter writer = ExcelUtil.getWriter(true);

		writer.addHeaderAlias("name", "姓名");
		writer.addHeaderAlias("age", "年龄");
		writer.addHeaderAlias("birthDay", "生日");

		/* 合并单元格后的标题行，使用默认标题样式 */
		writer.merge(2, "申请人员信息");

		/* 一次性写出内容，使用默认样式，强制输出标题 */
		writer.write(list, true);

		/* out为OutputStream，需要写出到的目标流 */

		/* response为HttpServletResponse对象 */
		response.setContentType("application/vnd.ms-excel;charset=utf-8");

//		String name = StringUtils.toUtf8String("test");
		String name = "test";
		response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xlsx");

		ServletOutputStream out = null;

		try {
			out = response.getOutputStream();
			writer.flush(out, true);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			writer.close();
		}
		IoUtil.close(out);
	}
}
